package com.beyondsoft.sabg.edu.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.beyondsoft.sabg.edu.model.db.core.BasicEntity;
import com.beyondsoft.sabg.edu.model.dto.ExportDTO;
import com.beyondsoft.sabg.edu.repository.core.SimpleRepository;
import com.beyondsoft.sabg.edu.service.ExportService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public abstract class AbstractExportServiceImpl<T extends BasicEntity, D extends ExportDTO,R extends SimpleRepository<T>>
        extends AbstractSimpleServiceImpl<T,R>
        implements ExportService<T,D,R> {
    @Override
    public void exportExcel(D dto, HttpServletResponse response) {
        Map<String,String> map = getBeanMapper();
        List data = getExportList(dto);
        ExcelWriter writer = ExcelUtil.getWriter(true);

        if (CollUtil.isNotEmpty(dto.getColumns())) {
            dto.getColumns().stream()
                    .filter(StrUtil::isNotBlank)
                    .forEach(c -> writer.addHeaderAlias(c, map.get(c)));
        }
        writer.setOnlyAlias(true);
        writer.write(data, true);
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
//test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=test.xls");
        ServletOutputStream excelOut = null;
        try {
            excelOut = response.getOutputStream();
            writer.flush(excelOut, true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            writer.close();
        }
        IoUtil.close(excelOut);
    }
    protected abstract List<T> getExportList(D dto);

    protected abstract Map getBeanMapper();
}
